package com.wnhoo.smartfishtank.fishtank;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wnhoo.smartfishtank.R;
import com.wnhoo.smartfishtank.api.LM_PlugAPIs;
import com.wnhoo.smartfishtank.api.LM_TimingAPI;
import com.wnhoo.smartfishtank.api.data.DataTiming;
import com.wnhoo.smartfishtank.api.data.LM_DataReceive;
import com.wnhoo.smartfishtank.api.data.LM_DataSend;
import com.wnhoo.smartfishtank.api.data.LM_DataStatus;
import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.base.BaseActivity;
import com.wnhoo.smartfishtank.brodcast.NetWorkChangeBroadcastReceiver;
import com.wnhoo.smartfishtank.contants.KContants;
import com.wnhoo.smartfishtank.ui.Color_picker;
import com.wnhoo.smartfishtank.ui.image;
import com.wnhoo.smartfishtank.util.MyLog;
import com.wnhoo.smartfishtank.util.SceneColor;
import com.wnhoo.smartfishtank.util.ShowToastUtil;
import com.wnhoo.smartfishtank.util.UIUtil;
import com.wnhoo.smartfishtank.util.UtilsHex;

import java.util.ArrayList;
import java.util.List;

public class ColorActivity extends BaseActivity implements BaseActivity.InitHeaderListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener
        , View.OnLongClickListener, Color_picker.OnColorChangedListener, image.OnColorChangedListener {

    private RelativeLayout light_color_bg, light_circle_rl_color;
    private Button light_color_btn_show, light_color_btn_close, thermostat_btn_add, thermostat_btn_subteact;
    public static TransitionDrawable[] localTransitionDrawable = new TransitionDrawable[2];
    public Drawable[] skin = new Drawable[2];
    private SeekBar seek_bar_warm, seek_bar_warm_timing_switch;
    private int max_seek = 100;
    private Button coler_red, coler_white, coler_yellow, coler_green, coler_blue, light_picker_btn;
    private Color_picker imageView_ring_color;
    private boolean isModel = true;//当前是日光还是彩光模式
    private boolean isThreadHttpReceive;
    private ThreadHttpReceive threadDeviceStatus;
    private boolean isTotalState = true;//当进行点击开关的时候，暂时不接收全状态数据，不然页面有时会连续跳转
    private TextView brightness_tv;
    private int value;
    private Button light_color_btn_switch;
    private static int timingSwitch;//定时功能总的开关状态
    private SharedPreferences share;
    private final String share_key_timng = "timing_list_json";//自定义的定时列表
    public List<DataTiming> list_timing = new ArrayList<>();//自定义的列表
    public List<DataTiming> list_timing_default = new ArrayList<>();//默认的定时列表
    public static ColorActivity instance;
    private boolean isFirstShow = true;//第一次从服务器显示加载定时状态的时候，不往服务器设置数据
    private ImageView control_pointer;
    private TextView color_online_tv;
    private byte[] colorByte;
    private String TAG = "ColorActivity";
    private String hex_color;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color);
        setOnInitListener(this);
        instance = this;
        initView();
        initData();
        Log.i(TAG, "初始化数据中");
//        Toast.makeText(ColorActivity.this, "" + LMAPP.dataPlug.getId(), Toast.LENGTH_LONG).show();
    }


    @Override
    public void initView() {
        super.initView();

        light_picker_btn = (Button) findViewById(R.id.light_picker_btn);
        light_circle_rl_color = (RelativeLayout) findViewById(R.id.light_circle_rl_color);
        light_color_bg = (RelativeLayout) findViewById(R.id.light_color_bg);
        light_color_btn_show = (Button) findViewById(R.id.light_color_btn_show);
        light_color_btn_close = (Button) findViewById(R.id.light_color_btn_close);
        light_color_btn_switch = (Button) findViewById(R.id.light_color_btn_switch);
        thermostat_btn_add = (Button) findViewById(R.id.thermostat_btn_add);
        thermostat_btn_subteact = (Button) findViewById(R.id.thermostat_btn_subteact);
        coler_red = (Button) findViewById(R.id.coler_red);
        coler_green = (Button) findViewById(R.id.coler_green);
        coler_blue = (Button) findViewById(R.id.coler_blue);
        coler_white = (Button) findViewById(R.id.coler_white);
        coler_yellow = (Button) findViewById(R.id.coler_yellow);
        seek_bar_warm = (SeekBar) findViewById(R.id.seek_bar_warm);
        seek_bar_warm_timing_switch = (SeekBar) findViewById(R.id.seek_bar_warm_timing_switch);
        brightness_tv = (TextView) findViewById(R.id.brightness_tv);
        imageView_ring_color = (Color_picker) findViewById(R.id.imageView_ring_color);
        control_pointer = (ImageView) findViewById(R.id.control_pointer);
        color_online_tv = (TextView) findViewById(R.id.ther_online_tv);
        light_color_btn_show.setOnClickListener(this);
        light_color_btn_close.setOnClickListener(this);
        thermostat_btn_add.setOnClickListener(this);
        light_color_btn_switch.setOnClickListener(this);
        imageView_ring_color.setOnColorChangedListenner(this);

        coler_red.setOnClickListener(this);
        coler_green.setOnClickListener(this);
        coler_blue.setOnClickListener(this);
        coler_white.setOnClickListener(this);
        coler_yellow.setOnClickListener(this);

        thermostat_btn_subteact.setOnClickListener(this);
        thermostat_btn_subteact.setOnLongClickListener(this);

        skin[0] = new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.temperature_bg_black));
        skin[1] = new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.thermostat_bg1));
        localTransitionDrawable[0] = new TransitionDrawable(new Drawable[]{new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.common_bg)), skin[0]});
        localTransitionDrawable[1] = new TransitionDrawable(new Drawable[]{new BitmapDrawable(UIUtil.getBitmap(this, R.drawable.common_bg)), skin[1]});
    }

    private void initData() {
        initTimingData();
        seek_bar_warm.setMax(max_seek);
        seek_bar_warm.setProgress(100);
        seek_bar_warm.setOnSeekBarChangeListener(this);
        seek_bar_warm_timing_switch.setOnSeekBarChangeListener(this);
        seek_bar_warm_timing_switch.setMax(max_seek);
        seek_bar_warm_timing_switch.setProgress(0);
        this.onStopTrackingTouch(seek_bar_warm_timing_switch);
        startHttpStatus();
        brightness_tv.setText(seek_bar_warm.getProgress() + "%");
        IntentFilter intentFilter = new IntentFilter(NetWorkChangeBroadcastReceiver.NETWORKCHANGE);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean isNetWork = intent.getBooleanExtra("isNetWork", true);
                if (isNetWork) {
                    color_online_tv.setText(getStringXml(R.string.device_connect));
                } else {
                    color_online_tv.setText(getStringXml(R.string.network_disconnect));
                }
            }
        }, intentFilter);
    }

    /**
     * 处理在线状态请求结果
     *
     * @param msg
     */
    public void handlerOnlineStatus(Message msg) {

        LM_DataStatus dataReceive = (LM_DataStatus) msg.obj;
        if (dataReceive == null) {
            return;
        }
        Log.d(TAG, "online=" + dataReceive.getOnline());

        if (LMAPP.dataPlug != null) LMAPP.dataPlug.setOnline(dataReceive.getOnline());
        if ("1".equals(dataReceive.getOnline())) {
            color_online_tv.setText(getStringXml(R.string.online));
        } else if ("0".equals(dataReceive.getOnline())) {
            color_online_tv.setText(getStringXml(R.string.offline));
        } else {
            color_online_tv.setText(getStringXml(R.string.online));
//            MyLog.s(tag,"Debug:没有解析出结果是离线还是在线，内容："+dataReceive.getOnline());
        }
    }

    /**
     * 初始化定时数据信息
     */
    private void initTimingData() {
        share = getSharedPreferences(KContants.SPF_PLUG_CONFIG, MODE_PRIVATE);
        String timing_value_json = share.getString(share_key_timng, null);
        AsyncTaskTiming async = new AsyncTaskTiming();
        Log.i(TAG, "timing_value_json" + timing_value_json);
        if (timing_value_json != null && !"".equals(timing_value_json)) {
            try {
                Log.d(TAG, "本地定时数据不为空");

                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<List<DataTiming>>() {
                }.getType();
                //把新添加的timing加到内存
                List<DataTiming> dataTimingList = gson.fromJson(timing_value_json, type);
                Log.i(TAG, "timing_value_json" + dataTimingList);
                for (DataTiming dataTiming : dataTimingList) {
                    list_timing.add(dataTiming);
                }
                Log.i(TAG, "timing_value_json" + dataTimingList.size());
                if (list_timing.size() != 6) {
                    setTiming_List(list_timing);
                }
                saveToSPF();

            } catch (Exception e) {
                SharedPreferences.Editor editor = share.edit();
                editor.putString(share_key_timng, "");
                editor.apply();
            } finally {
//                MyLog.d(TAG, "第一次运行，执行向服务器请求数据");
                async.execute("");
            }
        } else {
            Log.d(TAG, "本地定时数据为空，将请求Http同步数据");
            //如果本地的定时列表没有，初始化定时数据
            setTiming_List(list_timing);
            saveToSPF();
            async.execute("");
        }
    }

    public List<DataTiming> getList_timing() {
//        if(list_timing==null||list_timing.isEmpty()){
//            list_timing = new ArrayList<>();
//            setTiming_List(list_timing);
//        }
        Log.i(TAG, "当前自定义的数据是" + list_timing);
        return list_timing;
    }

    public List<DataTiming> getList_timing_default() {
//        if(list_timing_default==null||list_timing_default.isEmpty()){
//            list_timing_default = new ArrayList<>();
//            setTiming_List(list_timing_default);
//        }
        return list_timing_default;
    }

    private int switch_Isopen = 1;

    public int getTimingSwitch() {
        return timingSwitch;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.light_color_btn_show:
                if (!isModel) {
                    light_circle_rl_color.setVisibility(View.GONE);
                    light_color_btn_close.setVisibility(View.GONE);
                    light_color_btn_switch.setVisibility(View.VISIBLE);
                    control_pointer.setVisibility(View.GONE);
                    isModel = true;
                } else {
                    light_circle_rl_color.setVisibility(View.VISIBLE);
                    light_color_btn_close.setVisibility(View.VISIBLE);
                    light_color_btn_switch.setVisibility(View.GONE);
                    control_pointer.setVisibility(View.VISIBLE);
                    isModel = false;
                }
                break;
            case R.id.thermostat_btn_add:
                if (seek_bar_warm.getProgress() < 100) {
                    seek_bar_warm.setProgress(seek_bar_warm.getProgress() + 1);
                    brightness_tv.setText(seek_bar_warm.getProgress() + "%");
                }
                break;
            case R.id.thermostat_btn_subteact:
                if (seek_bar_warm.getProgress() > 0) {
                    seek_bar_warm.setProgress(seek_bar_warm.getProgress() - 1);
                    brightness_tv.setText(seek_bar_warm.getProgress() + "%");
                }
                break;
            case R.id.light_color_btn_switch:
                if (switch_Isopen == 0) {
                    light_color_bg.setBackground(localTransitionDrawable[0]);
                    localTransitionDrawable[0].startTransition(1000);
                    light_color_btn_switch.setBackgroundResource(R.drawable.light_switch_icon_close_closepicker);
                    switch_Isopen = 1;
                    sendColorToLight(new byte[]{0, 0, 0, 0, 0, 0}, seek_bar_warm.getProgress());
                    isTotalState = false;
                } else {
                    light_color_bg.setBackground(localTransitionDrawable[1]);
                    localTransitionDrawable[1].startTransition(1000);
                    light_color_btn_switch.setBackgroundResource(R.drawable.light_switch_icon_open_closepicker);
                    switch_Isopen = 0;
                    // Chimo
//                    sendColorToLight(new byte[]{-1, -1, -1, -1, -1, -1}, seek_bar_warm.getProgress());
                    sendColorToLight(new byte[]{0, 0, -1, -1, 0, 0}, seek_bar_warm.getProgress());
                    isTotalState = false;
                }
                break;
            case R.id.light_color_btn_close:
                if (switch_Isopen == 0) {
                    light_color_bg.setBackground(localTransitionDrawable[0]);
                    localTransitionDrawable[0].startTransition(1000);
                    light_color_btn_close.setBackgroundResource(R.drawable.light_switch_icon_close);
                    switch_Isopen = 1;
                    sendColorToLight(new byte[]{0, 0, 0, 0, 0, 0}, seek_bar_warm.getProgress());
                    isTotalState = false;
                } else {
                    light_color_bg.setBackground(localTransitionDrawable[1]);
                    localTransitionDrawable[1].startTransition(1000);
                    light_color_btn_close.setBackgroundResource(R.drawable.light_switch_icon_open);
                    switch_Isopen = 0;
//                    sendColorToLight(new byte[]{-1, -1, -1, -1, -1, -1}, seek_bar_warm.getProgress());
                    sendColorToLight(SceneColor.white(), seek_bar_warm.getProgress());
                    isTotalState = false;
                }
                break;
            case R.id.coler_red:
                sendColorToLight(SceneColor.red(), 100);
                colorByte = new byte[]{(byte) 0xff, 0x00, 0x00};
                break;
            case R.id.coler_green:
                sendColorToLight(SceneColor.green(), 100);
                colorByte = new byte[]{ 0x00,(byte)0xff, 0x00};
                break;
            case R.id.coler_blue:
                sendColorToLight(SceneColor.blue(), 100);
                colorByte = new byte[]{ 0x00, 0x00,(byte)0xff};
                break;
            case R.id.coler_white:
                sendColorToLight(SceneColor.white(), 100);
                colorByte = new byte[]{ (byte)0xff, (byte)0xff,(byte)0xff};
                break;
            case R.id.coler_yellow:
                sendColorToLight(SceneColor.yellow(), 100);
                colorByte = new byte[]{ (byte)0xff, (byte)0xff,0x00};
                break;
        }
    }

    /**
     * 不断请求设备当前开关状态
     */
    private class ThreadHttpReceive extends Thread {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (isThreadHttpReceive) {
                try {
                    if (LMAPP.dataPlug != null) {
                        LM_DataReceive data_status = LM_PlugAPIs.requestReceiveData(false, LMAPP.dataPlug.getId(), "S16", "1", LMAPP.getAccessToken());
                        LM_DataStatus data_status_online = LM_PlugAPIs.requestOnlineStatus(true, LMAPP.dataPlug.getId(), LMAPP.getAccessToken());
                        Log.i("i", "=====data_status" + data_status);
                        sendMessageToUI(MSG_HTTP_RECEIVE_FULL_STATUS, data_status);
                        sendMessageToUI(MSG_HTTP_ONLINE_STATUS, data_status_online);
                    }
                } catch (Exception e) {
                    //MyLog.exception(e);
                    sendMessageToUI(MSG_HTTP_RECEIVE_FULL_STATUS_EXCEPTION, e);
                    sendMessageToUI(MSG_HTTP_RECEIVE_FULL_STATUS_EXCEPTION, e);
                } finally {
//                    睡眠必须要执行到
                    try {
                        sleep(3 * 1000);
                    } catch (Exception e1) {
                    }
                }
            }
            super.run();
        }
    }

    public void startHttpStatus() {

        if (threadDeviceStatus == null) {
            //MyLog.i(tag,"startHttpStatus");
            isThreadHttpReceive = true;
            threadDeviceStatus = new ThreadHttpReceive();
            threadDeviceStatus.start();
        }
    }

    public void stopHttpStatus() {
        try {
            isThreadHttpReceive = false;
            if (threadDeviceStatus != null) {
                threadDeviceStatus.interrupt();
                threadDeviceStatus = null;
                //MyLog.i(tag,"stopHttpStatus");
            } else {
                //MyLog.e(tag, "HttpStatus is stop.");
            }
        } catch (Exception e) {
            // TODO: handle exception
            //MyLog.i(tag,"stopHttpStatus Exception:"+e.toString());
            //MyLog.exception(e);
        }
    }

    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()) {
            case R.id.thermostat_btn_add:
                if (seek_bar_warm.getProgress() < 100) {
                    seek_bar_warm.setProgress(seek_bar_warm.getProgress() + 1);
                }
            case R.id.thermostat_btn_subteact:
                if (seek_bar_warm.getProgress() > 0) {
                    seek_bar_warm.setProgress(seek_bar_warm.getProgress() - 1);
                }
        }
        return false;
    }

    @Override
    public void OnSetTitle(TextView t) {
        t.setText(getStringXml(R.string.fish_light));
    }

    @Override
    public void OnSetLeftView(Button btn) {
        btn.setVisibility(View.VISIBLE);
        btn.setBackgroundResource(R.drawable.light_back_selector);
    }

    @Override
    public void OnSetRightView(Button btn) {
        btn.setVisibility(View.VISIBLE);
        btn.setBackgroundResource(R.drawable.light_set_selector);
    }

    @Override
    public void OnSetLeftOnclick(View view) {
    }

    @Override
    public void OnSetRightOnclick(View view) {
        startActivity(new Intent(ColorActivity.this, Light_SettingActivity.class));
    }

    @Override
    public void onSetbackground(View view) {

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.seek_bar_warm:
                brightness_tv.setText(progress + "%");
                if (colorByte == null) {
                    sendColorToLight(new byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff}, progress);
                } else {
                    sendColorToLight(colorByte, progress);
                }
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        switch (seekBar.getId()) {
            case R.id.seek_bar_warm_timing_switch:
                //定时选择开始的时候
                value = seekBar.getProgress();
                if (value < 25) {
                    value = 0;
                    seekBar.setProgress(0);
                    timingSwitch = 1;
                    if (!isFirstShow) {
                        sendTiming();
                    }

                } else if (value >= 25 && value < 50 || value >= 50 && value < 75) {
                    //定时选择关闭的时候
                    value = 50;
                    seekBar.setProgress(50);
                    timingSwitch = 0;
                    if (!isFirstShow) {
                        sendTiming();
                    }
                } else if (value >= 75 && value <= 100) {
                    //定时选择默认的时候
                    value = 100;
                    seekBar.setProgress(100);
                    timingSwitch = 2;
                    if (!isFirstShow) {
                        sendDefultTiming();
                    }
                }
                isFirstShow = false;
                break;
        }
    }

    /**
     * 当选择打开/关闭定时时，
     */
    private void sendTiming() {
//        if(!isFirstShow){
//            return;
//        }
        sendToClound();
    }

    /**
     * 当选择默认定时，
     */
    private void sendDefultTiming() {
//        if(!isFirstShow){
//            return;
//        }
        if (list_timing_default.isEmpty()) {
            setTiming_List(list_timing_default);
        }
        Log.i(TAG, "list_timing_default" + list_timing_default.size());
        sendDefultToClound();
    }


    //Http
    private final static int MSG_HTTP_SEND_RESULT = 1;
    private final static int MSG_HTTP_SEND_EXCEPTION = 2;
    private final static int MSG_HTTP_RECEIVE_FULL_STATUS = 3;
    private final static int MSG_HTTP_RECEIVE_FULL_STATUS_EXCEPTION = 4;
    private final static int MSG_HTTP_RECEIVE_TIMING = 5;
    private final static int MSG_HTTP_RECEIVE_TIMING_EXCEPTION = 6;
    private final static int MSG_HTTP_ONLINE_STATUS = 7;
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_HTTP_SEND_RESULT:
                    //handlerSendResult(msg);
                    break;
                case MSG_HTTP_SEND_EXCEPTION:

                    break;
                case MSG_HTTP_RECEIVE_FULL_STATUS:
                    //设备返回它的全状态
                    handlerReceiveFullStatus(msg);
                    break;
                case MSG_HTTP_RECEIVE_FULL_STATUS_EXCEPTION:
                    //if(isDebug)debug_status.setText("Debug:"+msg.obj.toString());
                    break;
                case MSG_HTTP_RECEIVE_TIMING:
                    //定时数据的返回
                    //setOfflineTextView();
                    break;
                case MSG_HTTP_RECEIVE_TIMING_EXCEPTION:
//                    handlerOnlineStatus(msg);
                    break;
                case MSG_HTTP_ONLINE_STATUS:
                    handlerOnlineStatus(msg);
                    break;
                default:

                    break;
            }
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void handlerReceiveFullStatus(Message msg) {
        if (!isTotalState) {
            isTotalState = true;
            return;
        }
        //MyLog.TT("TEST",msg.obj.toString());
        LM_DataReceive dataReceive = (LM_DataReceive) msg.obj;
        if (dataReceive == null) {
            Log.i("return", "dataReceive==null");
            return;
        }
        Log.i("return", "dataReceive" + dataReceive.toString());
        if (dataReceive.getValue().equals("000000")) {
            light_color_bg.setBackground(localTransitionDrawable[0]);
//            localTransitionDrawable[0].startTransition(1000);
            light_color_btn_close.setBackgroundResource(R.drawable.light_switch_icon_close);
            switch_Isopen = 1;
        } else if (dataReceive.getValue().equals("ffffff")) {
            light_color_bg.setBackground(localTransitionDrawable[1]);
//            localTransitionDrawable[1].startTransition(1000);
            light_color_btn_close.setBackgroundResource(R.drawable.light_switch_icon_open);
            switch_Isopen = 0;
        }
    }

    public void sendMessageToUI(int what, Object obj) {

        Message message = Message.obtain();
        message.what = what;
        message.obj = obj;
        handler.sendMessage(message);
    }

    //控制颜色
    public void sendControlPlugHttp(final String color) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    LM_DataSend dataSend = LM_PlugAPIs.requestSendLightSetcolor(true, LMAPP.dataPlug.getId(), color, LMAPP.token_default);
                    //DataSend dataSend = PlugAPIs.requestSendControl(true, dataPlug.getId(), type,plugActivity.getToken() );
                    sendMessageToUI(MSG_HTTP_SEND_RESULT, dataSend);
                    ////MyLog.s(tag,version.toString());
                } catch (Exception e) {
                    //MyLog.exception(e);
                    sendMessageToUI(MSG_HTTP_SEND_EXCEPTION, e);
                }
            }
        }.start();
    }

    @Override
    public void onColorChanging(int color) {
        handlerSelectColor(color, seek_bar_warm.getProgress());
    }

    public void handlerSelectColor(int color, int brightness) {
        try {
            hex_color = Integer.toHexString(color).toUpperCase().substring(2);
            Log.i("i", "=====hex_color" + hex_color);
            colorByte = UtilsHex.hexStringToBytes(hex_color);
            sendColorToLight(colorByte, brightness);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendColorToLight(byte[] color_byte, int brightness) {
        //if(brightness<=5)brightness=5;
        byte[] valueColor = new byte[3];
        valueColor[0] = (byte) (((color_byte[0] & 0xFF) * brightness / 100) & 0xff);//red
        valueColor[1] = (byte) (((color_byte[1] & 0xFF) * brightness / 100) & 0xff);//green
        valueColor[2] = (byte) (((color_byte[2] & 0xFF) * brightness / 100) & 0xff);//blue
        String color = UtilsHex.bytesToHexString(valueColor);

        Log.i(TAG,"app发送数据下去"+color);
        sendControlPlugHttp(color);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopHttpStatus();
    }

    /**
     * 向服务器请求定时列表数据
     */
    public class AsyncTaskTiming extends AsyncTask<String, Integer, LM_DataReceive> {//继承AsyncTask

        @Override
        protected LM_DataReceive doInBackground(String... params) {//处理后台执行的任务，在后台线程执行

            LM_DataReceive dataReceive = null;
            try {
                Log.d(TAG, "请求服务器存储的定时数据requestTimingList");
                dataReceive = LM_TimingAPI.requestTimingList(LMAPP.dataPlug.getId(), LMAPP.token_default);
                Log.d(TAG, "请求服务器存储的定时数据requestTimingList" + dataReceive);
            } catch (Exception e) {
                MyLog.exception(e);
            }
            return dataReceive;
        }

        protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用，在ui线程执行
        }

        protected void onPostExecute(LM_DataReceive dataReceive) {//后台任务执行完之后被调用，在ui线程执行
            if (dataReceive.getValue().equals("null")) return;

            //获取当前设备是开启，关闭还是默认
            Log.d(TAG, "请求服务器存储的定时数据timingSwitch" + dataReceive.getValue());
            timingSwitch = Integer.parseInt(dataReceive.getValue().substring(0, 1));
            Log.d(TAG, "请求服务器存储的定时数据timingSwitch" + timingSwitch);
            setTimingProess(timingSwitch);
            List<DataTiming> list = getReceviceTiming(dataReceive);
            saveToSPF();
            Log.d(TAG, "请求服务器存储的定时数据requestTimingList" + list_timing.size());
        }

        protected void onPreExecute() {//在 doInBackground(Params...)之前被调用，在ui线程执行
        }

        protected void onCancelled() {//在ui线程执行
        }
    }

    /**
     * 设置定时滑动条的位置
     */
    private void setTimingProess(int type) {
        switch (type) {
            case 0:
                seek_bar_warm_timing_switch.setProgress(50);
                break;
            case 1:
                seek_bar_warm_timing_switch.setProgress(0);
                break;
            case 2:
                seek_bar_warm_timing_switch.setProgress(100);
                break;
        }
    }

    /**
     * 解析得到的定时数据
     *
     * @param dataReceive
     */
    private List<DataTiming> getReceviceTiming(LM_DataReceive dataReceive) {
        if (dataReceive == null || dataReceive.getError_code() != 0) return null;
        String value = dataReceive.getValue();
        if(value.length()!=21){
            setTiming_List(list_timing);
            return null;
        }
        int left_parenthesis = value.indexOf("(");
        int right_parenthesis = value.indexOf(";)");
        String value_sub = value.substring(left_parenthesis + 1, right_parenthesis);
        String[] timer_temp_array = value_sub.split(",");
        if (timer_temp_array.length != 6) {
            return null;
        }
        //（01,02,03,04,10,16;）
        for (int i = 0; i < timer_temp_array.length; i++) {
            Log.i(TAG, "当前设备的列表是" + timer_temp_array[i]);

            list_timing.get(i).setColor(timer_temp_array[i]);
        }
        if (list_timing.isEmpty()) return null;
        Log.i(TAG, "当前设备的列表是" + list_timing);
        return list_timing;
    }

    /**
     * 向服务器发送自定义定时数据
     */
    class AsyncTaskSend extends AsyncTask<String, Integer, LM_DataSend> {//继承AsyncTask

        @Override
        protected LM_DataSend doInBackground(String... params) {//处理后台执行的任务，在后台线程执行
            LM_DataSend data = null;
            if (list_timing.size() != 6) {
                setTiming_List(list_timing);
            }
            try {
                data = LM_TimingAPI.sendTimingList(list_timing, LMAPP.dataPlug.getId(), LMAPP.token_default, timingSwitch);
            } catch (Exception e) {
                MyLog.exception(e);
            }
            return data;
        }

        protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用，在ui线程执行
        }

        protected void onPostExecute(LM_DataSend data) {//后台任务执行完之后被调用，在ui线程执行
            Log.i(TAG, "LM_DataSend" + data);
            if (data != null && data.isResult()) {
                setTimingProess(timingSwitch);
                if (timingSwitch == 0) {
                    ShowToastUtil.showShort(getApplication(), getStringXml(R.string.timing_close));
                } else if (timingSwitch == 1) {
                    ShowToastUtil.showShort(getApplication(), getStringXml(R.string.timing_open));
                } else if (timingSwitch == 2) {
                    ShowToastUtil.showShort(getApplication(), getStringXml(R.string.timing_dafult));
                }
            } else {
                ShowToastUtil.showShort(getApplication(), getStringXml(R.string.operation_failure));
//                saveToSPF();
            }
        }

        protected void onPreExecute() {//在 doInBackground(Params...)之前被调用，在ui线程执行
        }

        protected void onCancelled() {//在ui线程执行
        }
    }

    /**
     * 向服务器发送默认定时数据
     */
    class AsyncTaskSendDefult extends AsyncTask<String, Integer, LM_DataSend> {//继承AsyncTask

        @Override
        protected LM_DataSend doInBackground(String... params) {//处理后台执行的任务，在后台线程执行
            LM_DataSend data = null;
            try {
                data = LM_TimingAPI.sendTimingList(list_timing_default, LMAPP.dataPlug.getId(), LMAPP.token_default, timingSwitch);
            } catch (Exception e) {
                MyLog.exception(e);
            }
            return data;
        }

        protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用，在ui线程执行
        }

        protected void onPostExecute(LM_DataSend data) {//后台任务执行完之后被调用，在ui线程执行
            Log.i(TAG, "LM_DataSend" + data);
            if (data != null && data.isResult()) {
                setTimingProess(timingSwitch);
                if (timingSwitch == 0) {
                    ShowToastUtil.showShort(getApplication(), getStringXml(R.string.timing_close));
                } else if (timingSwitch == 1) {
                    ShowToastUtil.showShort(getApplication(), getStringXml(R.string.timing_open));
                } else if (timingSwitch == 2) {
                    ShowToastUtil.showShort(getApplication(), getStringXml(R.string.timing_dafult));
                }
            } else {
                ShowToastUtil.showShort(getApplication(), getStringXml(R.string.operation_failure));
//                saveToSPF();
            }
        }

        protected void onPreExecute() {//在 doInBackground(Params...)之前被调用，在ui线程执行
        }

        protected void onCancelled() {//在ui线程执行
        }
    }

    public void saveToSPF() {
        MyLog.d(TAG, "saveToSPF--------------------------------------------");
        Gson gson = new Gson();
        SharedPreferences.Editor editor = share.edit();
        editor.putString(share_key_timng, gson.toJson(list_timing));
        editor.apply();
    }


    /**
     * 将自定义数据发送到服务器
     */
    public void sendToClound() {
        MyLog.e(TAG, "sendToClound->");
        AsyncTaskSend asy = new AsyncTaskSend();
        asy.execute("");
    }

    /**
     * 将默认定时数据发送到服务器
     */
    public void sendDefultToClound() {
        MyLog.e(TAG, "sendDefultToClound->");
        AsyncTaskSendDefult asy = new AsyncTaskSendDefult();
        asy.execute("");
    }

    /**
     * 设置列表的默认数据;默认6组定时
     */
    public void setTiming_List(List<DataTiming> timing) {
        timing.clear();
        DataTiming dataTiming = new DataTiming();
        dataTiming.setTime_open("08:00");
        dataTiming.setTime_colse("09:00");
        dataTiming.setColor("00");
        dataTiming.setSend_timing(true);
        dataTiming.setPerion_value("ff");
        timing.add(dataTiming);
        dataTiming = new DataTiming();
        dataTiming.setTime_open("09:00");
        dataTiming.setTime_colse("10:00");
        dataTiming.setColor("01");
        dataTiming.setSend_timing(true);
        dataTiming.setPerion_value("ff");
        timing.add(dataTiming);
        dataTiming = new DataTiming();
        dataTiming.setTime_open("10:00");
        dataTiming.setTime_colse("14:00");
        dataTiming.setColor("02");
        dataTiming.setSend_timing(true);
        dataTiming.setPerion_value("ff");
        timing.add(dataTiming);
        dataTiming = new DataTiming();
        dataTiming.setTime_open("14:00");
        dataTiming.setTime_colse("18:00");
        dataTiming.setColor("03");
        dataTiming.setSend_timing(true);
        dataTiming.setPerion_value("ff");
        timing.add(dataTiming);
        dataTiming = new DataTiming();
        dataTiming.setTime_open("18:00");
        dataTiming.setTime_colse("22:00");
        dataTiming.setColor("04");
        dataTiming.setSend_timing(true);
        dataTiming.setPerion_value("ff");
        timing.add(dataTiming);
        dataTiming = new DataTiming();
        dataTiming.setTime_open("22:00");
        dataTiming.setTime_colse("08:00");
        dataTiming.setColor("05");
        dataTiming.setSend_timing(true);
        dataTiming.setPerion_value("ff");
        timing.add(dataTiming);
    }
}
